package com.ndood.payment.core.security.handler;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ndood.payment.core.constaints.PCode;
import com.ndood.payment.pojo.v1.comm.vo.PaymentResultVo;

import lombok.extern.slf4j.Slf4j;

@Component("authenctiationFailureHandler")
@Slf4j
public class PaymentAuthenticationFailureHandler  extends SimpleUrlAuthenticationFailureHandler{

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {

		// 根据配置进行处理
		// response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		response.setStatus(HttpStatus.OK.value());
		response.setContentType("application/json;charset=UTF-8");
		
		String json = objectMapper.writeValueAsString(
				PaymentResultVo.error().setCode(PCode.ERR_TOKEN.getCode()).setMsg(exception.getMessage()));

		StringBuilder sb = new StringBuilder("\n");
		sb.append("BBBBBBBBBBBBBBB登录失败开始BBBBBBBBBBBBBBB").append("\n");
		sb.append(JSON.toJSON(getHeadersInfo(request))).append("\n");
		sb.append(JSON.toJSON(request.getParameterMap())).append("\n");
		sb.append("返回结果:").append(json).append("\n");
		sb.append("BBBBBBBBBBBBBBB登录失败结束BBBBBBBBBBBBBBB").append("\n\n");
		log.error(sb.toString(), exception);

		response.getWriter().write(json);
		response.getWriter().flush();

	}
	
	/**
	 * 获取请求头信息
	 */
	private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
	
}
